<template>
  <div id="_adaptive">
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
let props = defineProps({
  option: {
    type: Object,
    default: {
      width: 1920,
      height: 1080,
    }
  },
  fullScreen: {
    type: Boolean,
    default: false
  }
})
const option = props.option
let timeout;
function debounce(func, wait) {
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

let adaptive = ref(null)

onMounted(() => {
  adaptive.value = document.querySelector('#_adaptive')
  adaptive.value.style.transformOrigin = 'top left'
  adaptive.value.style.transition = `transform 0.2s`
  autoScale()
  window.addEventListener('resize', debounce(autoScale, 200))
})
const clearListener = () => {
  window.removeEventListener('resize', debounce(autoScale, 200))
}
onUnmounted(() => {
  clearListener()
})
const options = {
  width: option.width,
  height: option.height
}

const autoScale = () => {
  const { width, height } = options
  function init() {
    const scaleX = innerWidth / width
    const scaleY = innerHeight / height
    const scale = Math.min(scaleX, scaleY)

    const left = (innerWidth - width * scale) / 2
    const top = (innerHeight - height * scale) / 2

    if (props.fullScreen) {
      adaptive.value.style.transform = `scale(${scaleX},${scaleY})`
      return false
    }
    adaptive.value.style.transform = `translate(${left}px, ${top}px) scale(${scale})`
  }
  init()
}

</script>

<style lang="scss" scoped>
#_adaptive {}
</style>